<template>
  <a-card :bordered="false" :bodyStyle="{ padding: '24px 0', height: '100%' }">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="搜索学员:">
              <a-input v-model="keywords" placeholder="搜索学员/手机号(回车搜索)" style="width:80%;"
                @pressEnter="$refs.table.refresh(true)">
                <a-tooltip slot="suffix" title="搜索学员/手机号">
                  <a-icon type="search" style="color: rgba(0,0,0,.45)" @click="$refs.table.refresh(true)" />
                </a-tooltip>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="所在班级:">
              <a-select v-model="queryParam.class_id" style="width:80%;" placeholder="请选择所在班级" allowClear>
                <a-select-option v-for="(item, index) in Isclass" :key="index" :value="item.id">{{ item.name
                  }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="微信绑定状态:">
              <a-select v-model="queryParam.is_wechat" style="width:80%;" placeholder="请选择状态" allowClear>
                <a-select-option :value="false">未绑定</a-select-option>
                <a-select-option :value="true">已绑定</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="班级老师:">
                <a-select v-model="queryParam.teacher_id" style="width:80%;" placeholder="请选择班级老师" allowClear>
                  <a-select-option v-for="(item, index) in teacherList" :key="index" :value="item.id">{{ item.name
                    }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="跟进人:">
                <a-select v-model="queryParam.user_id" style="width:80%;" placeholder="请选择跟进人" allowClear>
                  <a-select-option v-for="(item, index) in userList" :key="index" :value="item.id">{{ item.name
                    }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="学管师:">
                <a-select v-model="queryParam.academic_supervisor" style="width:80%;" placeholder="请选择学管师" allowClear>
                  <a-select-option v-for="(item, index) in userList" :key="index" :value="item.id">{{ item.name
                    }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="生日月份:">
                <a-select v-model="queryParam.month" style="width:80%;" placeholder="请选择生日月份" allowClear>
                  <a-select-option v-for="(item, index) in monthList" :key="index" :value="item.id">{{ item.name
                    }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="标签">
                <a-select mode="multiple" placeholder="请选择标签" style="width:80%;" v-model="queryParam.label_id">
                  <a-select-option v-for="(item, index) in tagSelect" :key="index" :value="item.id">{{ item.content
                    }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-model-item label="学生来源">
                <a-select v-model="queryParam.source_id" placeholder="请选择学生来源" style="width:80%;" allowClear>
                  <a-select-option v-for="(item, index) in sourceSelect" :key="index" :value="item.id">{{ item.name
                    }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="最后跟进时间">
                <a-range-picker @change="onChange" style="width:80%;" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="下次跟进时间">
                <a-range-picker @change="onChange1" style="width:80%;" />
              </a-form-item>
            </a-col>
          </template>
          <!-- <a-col :md="!advanced && 8 || 24" :sm="24">
            <span
              class="table-page-search-submitButtons"
              :style="advanced && { float: 'right', overflow: 'hidden' } || {} "
            >
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>-->
        </a-row>
      </a-form>
    </div>
    <a style="cursor:pointer" v-if="advanced" @click="more" id="moreButton">
      收起
      <a-icon type="up"></a-icon>
    </a>
    <a style="cursor:pointer" v-if="!advanced" @click="more" id="moreButton">
      展开
      <a-icon type="down"></a-icon>
    </a>
    <div class="table-operator">
      <a-button type="primary" @click="$refs.followUp.showVisible()">今日待跟进({{ followUpCount.unComplete || '0'
        }})</a-button>
      <router-link v-if="selectedRowKeys.length == 0" :to="{ name: 'student_sendMessage' }"
        key="/educationalCenter/studentExpand/sendMessage">
        <a-button style="margin-left:10px;">发消息</a-button>
      </router-link>
      <a-button :disabled="selectedRowKeys.length == 0" @click="showUser(selectedRows)"
        style="margin-left:10px;">批量分配跟进人</a-button>
      <a-button :disabled="selectedRowKeys.length == 0" @click="showManager(selectedRows)"
        style="margin-left:10px;">批量分配学管师</a-button>
    </div>
    <!-- <a-alert type="warning" message="预警值： 剩余课时≤7课时 或 剩余天数≤10天" banner class="expand_warning" /> -->
    <s-table ref="table" :rowKey="(record) => record.id" :columns="columns" :data="loadData"
      class="user_management_table" style="margin-top:20px;"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :scroll="{ x: 2300 }"
      :pagination="pagination">
      <span slot="name" slot-scope="text,record">
        <a @click="nowClick(record)">{{ record.name }}</a>
        <a-icon type="man" v-if="record.sex == 1" style="color:#1890ff;margin-left:5px;" />
        <a-icon type="woman" v-if="record.sex == 2" style="color:#eb2f96;margin-left:5px;" />
      </span>
      <span slot="phone" slot-scope="text,record">
        <span style="margin-right:10px;">{{ record.main_phone }}</span>
        <a title="已绑定微信" @click="sendMessage(record)">
          <a-icon type="wechat" style="color:#52c41a" v-if="record.is_wechat" />
        </a>
        <a-icon type="wechat" v-if="!record.is_wechat" />
      </span>
      <span slot="action" slot-scope="text,record">
        <a @click="followUpStudent(record)">跟进</a>
        <a-divider type="vertical" />
        <a @click="showLessonTable(record)">试听</a>
        <a-divider type="vertical" />
        <a @click="signUp(record)">报名</a>
      </span>
    </s-table>
    <a-modal :visible="creat_visible" title="添加跟进记录" @ok="sure" @cancel="creat_visible = false"
      :confirmLoading="btnLoading" :bodyStyle="{ 'max-height': '400px', 'overflow-y': 'auto' }">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="跟进内容" prop="content">
          <a-textarea v-model="form.content" placeholder="请输入跟进内容" :maxLength="1000"
            :auto-size="{ minRows: 3, maxRows: 5 }" />
          <a-upload :before-upload="beforeUpload" list-type="picture-card" :file-list="fileList" :remove="removePic">
            <!-- @change="handleChange" -->
            <div v-if="fileList.length < 9">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-model-item>
        <a-form-model-item label="下次跟进">
          <a-date-picker v-model="time" show-time format="YYYY-MM-DD HH:mm" placeholder="选择时间" @change="changeTime"
            :disabled-date="disabledDate" />
        </a-form-model-item>
      </a-form-model>
      <div class="lastFollow" v-if="lastInfo">
        <div class="title">上次跟进记录</div>
        <div class="userInfo">
          <span class="user" style="margin-right:15px;">
            <a-icon type="user" style="margin-right:10px;color:#ccc;" />
            <span v-if="lastInfo.user && lastInfo.user.name"></span>
            <span v-else>--</span>
          </span>
          <!-- <span class="time">
            <a-icon type="clock-circle" style="margin-right:10px;color:#ccc;" />
          </span>-->
        </div>
        <div class="followUpContent">
          <span v-if="lastInfo.content">{{ lastInfo.content }}</span>
          <span v-else>--</span>
        </div>
      </div>
    </a-modal>
    <create-form ref="createModal" @ok="handleOk" />
    <!-- <step-by-step-modal ref="modal" @ok="handleOk" /> -->
    <listen-lesson-table ref="lessonTable" :student_id="studentID"></listen-lesson-table>
    <user-modal ref="user" @reload="$refs.table.refresh()"></user-modal>
    <user-modal-manager ref="manager" @reload="$refs.table.refresh()"></user-modal-manager>
    <follow-up-table-modal :studentFileExpand="1" ref="followUp"></follow-up-table-modal>
    <div class="ant-card" style="margin-top: 30px;padding: 30px;">
      <h2>在读学员</h2>
      <div style="display: flex; justify-content: space-around;">
        <div class="echart">
          <h1>{{ title }}</h1>
          <div class="echart" id="lineDemo" ref="chart" style="width: 1200px;height: 500px;"></div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
// import StepByStepModal from '../../list/modules/StepByStepModal'
import CreateForm from '@/views/list/modules/CreateForm'
import { studentList, studentFollowAdd } from '@/api/student'
import { classList } from '@/api/class'
import { uploadPic } from '@/api/login'
import { teacherList } from '@/api/teacher'
import { accountList } from '@/api/account'
import { tagList } from '@/api/tag'
import { sourceList } from '@/api/sources'
import listenLessonTable from '@/components/lesson'
import userModal from '@/components/userModel/user'
import userModalManager from '@/components/userModel/manager'
import followUpTableModal from '@/components/followUpTable'
import { followUp } from '@/api/dashboardCount'
export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    listenLessonTable,
    userModal,
    userModalManager,
    followUpTableModal,
    // StepByStepModal
  },
  data() {
    return {
      option: {
        title: {
          text: 'Current students'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['测试课程1', '测试课程2', '测试课程3', '测试课程4', '测试课程5'],
          textStyle: {
            color: '#a1a1a1'
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '测试课程1',
            type: 'line',
            stack: 'Total',
            areaStyle: {
              color: 'rgba(136, 155, 216)' // 单一颜色
            },
            lineStyle: {
              color: 'rgb(136, 155, 216)' // 线条颜色
            },
            emphasis: {
              focus: 'series'
            },
            data: [120, 132, 101, 134, 90, 230, 210]
          },
          {
            name: '测试课程2',
            type: 'line',
            stack: 'Total',
            areaStyle: {
              color: 'rgba(178, 220, 159)' // 单一颜色
            },
            lineStyle: {
              color: 'rgba(178, 220, 159)' // 单一颜色
            },
            emphasis: {
              focus: 'series'
            },
            data: [220, 182, 191, 234, 290, 330, 310]
          },
          {
            name: '测试课程3',
            type: 'line',
            stack: 'Total',
            areaStyle: {
              color: 'rgba(252, 217, 139)' // 单一颜色
            },
            lineStyle: {
              color: 'rgba(252, 217, 139)' // 单一颜色
            },
            emphasis: {
              focus: 'series'
            },
            data: [150, 232, 201, 154, 190, 330, 410]
          },
          {
            name: '测试课程4',
            type: 'line',
            stack: 'Total',
            areaStyle: {
              color: 'rgba(244,148, 148)' // 单一颜色
            },
            lineStyle: {
              color: 'rgba(244,148, 148)' // 单一颜色
            },
            emphasis: {
              focus: 'series'
            },
            data: [320, 332, 301, 334, 390, 330, 320]
          },
          {
            name: '测试课程5',
            type: 'line',
            stack: 'Total',
            label: {
              show: true,
              position: 'top'
            },
            areaStyle: {
              color: 'rgba(157, 211, 232)' // 单一颜色
            },
            lineStyle: {
              color: 'rgba(157, 211, 232)' // 单一颜色
            },
            emphasis: {
              focus: 'series'
            },
            data: [820, 932, 901, 934, 1290, 1330, 1320]
          }
        ]
      },
      pagination: {
        showTotal: total => `共${total}条数据`
      },
      mdl: {},
      selectedRowKeys: [],
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      keywords: '',
      queryParam: {
        type: 1,
        school_id: this.$store.state.user.school,

      },
      // 班级数据
      Isclass: [],
      //教室数据
      teacherList: [],
      userList: [],
      //生日月份数据
      monthList: [
        {
          id: 1,
          name: '一月',
        },
        {
          id: 2,
          name: '二月',
        },
        {
          id: 3,
          name: '三月',
        },
        {
          id: 4,
          name: '四月',
        },
        {
          id: 5,
          name: '五月',
        },
        {
          id: 6,
          name: '六月',
        },
        {
          id: 7,
          name: '七月',
        },
        {
          id: 8,
          name: '八月',
        },
        {
          id: 9,
          name: '九月',
        },
        {
          id: 10,
          name: '十月',
        },
        {
          id: 11,
          name: '十一月',
        },
        {
          id: 12,
          name: '十二月',
        },
      ],
      tagSelect: [], //标签
      sourceSelect: [], //学生来源下拉
      queryParams: {
        user_type: 0,
        type: 1,
        school_id: this.$store.state.user.school,


      },
      // 表头
      columns: [
        {
          title: '学员姓名',
          dataIndex: 'name',
          width: 200,
          fixed: 'left',
          ellipsis: true,
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '手机号',
          fixed: 'left',
          width: 200,
          dataIndex: 'main_phone',
          scopedSlots: { customRender: 'phone' },
        },

        {
          title: '年级',
          width: 150,
          dataIndex: 'grade_name',
        },
        {
          title: '年龄',
          width: 100,
          dataIndex: 'age',
          align: 'center',
        },
        {
          title: '出生日期',
          dataIndex: 'birthday',
        },
        {
          title: '学校',
          dataIndex: 'school_name',
          ellipsis: true,
          align: 'center', //  scopedSlots: { customRender: 'actions' },
        },
        {
          title: '创建时间',
          dataIndex: 'created_at',
          width: 250,
          ellipsis: true,
        },
        {
          title: '最后一次跟进',
          width: 150,
          dataIndex: 'last_follow_up',
          ellipsis: true,
        },
        {
          title: '下次跟进时间',
          width: 150,
          dataIndex: 'next_follow_up',
          ellipsis: true,
        },
        {
          title: '标签',
          width: 200,
          ellipsis: true,
          dataIndex: 'label_name',
          ellipsis: true,
        },
        {
          title: '学员来源',
          dataIndex: 'source_name',
          ellipsis: true,
        },
        {
          title: '跟进人',
          dataIndex: 'user_name',
          ellipsis: true,
        },
        {
          title: '学管师',
          dataIndex: 'academic_supervisor_name',
          ellipsis: true,
        },
        {
          title: '操作',
          //   width: '100px',
          dataIndex: 'action',
          fixed: 'right',
          align: 'right',
          ellipsis: true,
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return studentList(Object.assign(parameter, this.queryParam, { keywords: this.keywords })).then((res) => {
          return res
        })
      },
      studentID: null,
      creat_visible: false,
      form: {
        content: '',
        time: '',
      },
      rules: {
        content: [{ required: true, message: '请输入跟进内容', trigger: 'blur' }],
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      previewVisible: false,
      previewImage: '',
      fileList: [],
      visibleType: '',
      time: null,
      imgModal: '',
      showImgModal: false,
      btnLoading: false,

      followUpCount: {
        unComplete: 0,
        complete: 0,
      },
      lastInfo: null,
    }
  },
  created() {
    followUp(this.queryParams).then((res) => {
      this.followUpCount.unComplete = res.unComplete
      this.followUpCount.complete = res.complete
    })
    // this.tableOption()
    // getRoleList({ t: new Date() })
    // 获取班级信息
    classList({ pageSize: 999999, school_id: this.$store.state.user.school })
      .then((res) => {
        //搜索班级--keywords，名字字段
        this.Isclass = res.data
      })
      .catch((err) => {
        this.$message.error(err.data.message || '获取班级数据失败，请刷新页面或稍后再试')
      })
    teacherList({ pageSize: 999999, school_id: this.$store.state.user.school })
      .then((res) => {
        this.teacherList = res.data
      })
      .catch((err) => {
        this.$message.error(err.data.message || '获取教师数据失败，请刷新页面或稍后再试')
      })
    //跟进人
    accountList({ pageSize: 999999, school_id: this.$store.state.user.school })
      .then((res) => {
        this.userList = res.data
      })
      .catch((err) => {
        this.$message.error(err.data.message || '获取跟进人数据失败，请刷新页面或稍后再试')
      })
    //标签
    tagList({ pageSize: 999999, school_id: this.$store.state.user.school })
      .then((res) => {
        this.tagSelect = res.data
      })
      .catch((err) => {
        this.$message.error(err.data.message || '获取标签数据失败，请刷新页面或稍后再试')
      })
    //来源
    sourceList({ pageSize: 999999, school_id: this.$store.state.user.school })
      .then((res) => {
        this.sourceSelect = res.data
      })
      .catch((err) => {
        this.$message.error(err.data.message || '获取学生来源数据失败，请刷新页面或稍后再试')
      })
  },
  watch: {
    creat_visible(val) {
      if (val == false) {
        this.previewVisible = false
        this.previewImage = ''
        this.fileList = []
        this.visibleType = ''
        this.form = {
          content: '',
          time: '',
        }
        this.btnLoading = false
        this.time = undefined
      }
    },
    queryParam: {
      handler(newName, oldName) {
        this.$refs.table.refresh()
      },
      //immediate:true代表如果在 wacth 里声明了obj之后，就会立即先去执行里面的handler方法，
      immediate: false,
      deep: true, // 开启深度监听，默认是false
    },
  },
  mounted() {
    const chartDom = document.getElementById('lineDemo')
    const myChart = this.$echarts.init(chartDom)
    myChart.clear()
    myChart.setOption(this.option)
  },
  methods: {
    handleButtonClick(e) {
      console.log('click', e)
    },
    handleMenuClick(e) {
      console.log('click', e)
    },
    disabledDate(current) {
      return current && current < moment().startOf('day')
    },
    changeTime(date, dateString) {
      this.form.time = dateString
    },
    onChange(date, dateString) {
      this.queryParam.last_start_time = dateString[0]
      this.queryParam.last_end_time = dateString[1]
      this.$refs.table.refresh()
    },
    onChange1(date, dateString) {
      this.queryParam.next_start_time = dateString[0]
      this.queryParam.next_end_time = dateString[1]
      this.$refs.table.refresh()
    },

    sure() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          let params = JSON.parse(JSON.stringify(this.form))
          params.student_id = this.studentID
          params.img = []
          this.fileList.forEach((val) => {
            params.img.push(val.url)
          })
          if (this.time) {
            params.next_time = this.time.format('YYYY-MM-DD HH:mm')
          }
          studentFollowAdd(params)
            .then((res) => {
              this.$message.success('添加成功')
              this.creat_visible = false
              this.btnLoading = false
              // this.getList()
              this.$router.push({ name: 'student_Info', query: { id: this.studentID } })
            })
            .catch((err) => {
              this.$message.error(err.data.message || '添加失败，请稍后重试')
              this.btnLoading = false
            })
        } else {
          return false
        }
      })
    },
    followUpStudent(e) {
      this.studentID = e.id
      this.lastInfo = e.last
      this.creat_visible = true
    },
    showLessonTable(e) {
      this.studentID = e.id
      this.$refs.lessonTable.showVisible()
    },
    removePic(a) {
      this.fileList.forEach((item, index) => {
        if (item.uid == a.uid) {
          this.fileList.splice(index, 1)
        }
      })
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/svg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif'
      if (!isJpgOrPng) {
        this.$message.error('只能上传jpg/png图片格式！')
        return
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('只能上传10MB以内的图片!')
        return
      }
      const _this = this
      const formData = new FormData()
      formData.append('file', file)
      formData.append('school_id', this.$store.state.user.school)
      this.btnLoading = true
      uploadPic(formData)
        .then((res) => {
          this.fileList.push({
            name: res.path,
            uid: this.fileList.length + 1,
            url: res.url,
          })
          this.btnLoading = false
        })
        .catch((err) => {
          this.btnLoading = false
          this.$message.error(err.data.message || '上传失败，请稍后重试~')
        })
      return false
    },
    nowClick(e) {
      this.$router.push({ name: 'student_Info', query: { id: e.id } })
    },

    handleEdit(record) { },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    showUser(data) {
      let arr = []
      data.forEach((val) => {
        arr.push(val.id)
      })
      this.$refs.user.showModal(arr)
    },
    showManager(data) {
      let arr = []
      data.forEach((val) => {
        arr.push(val.id)
      })
      this.$refs.manager.showModal(arr)
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
    signUp(e) {
      this.$router.push({ name: 'apply', query: { id: e.id } })
    },
    more() {
      this.advanced = !this.advanced
    },
  },
}
</script>
<style lang="less" scoped>
.lastFollow {
  padding: 0 16px 16px;
  border-radius: 4px;
  background: #fafafa;

  .title {
    padding: 8px 0;
    border-bottom: 1px dashed #ccc;
  }

  .userInfo {
    padding: 8px 0;
  }
}

.expand_warning {
  margin: 16px 0;
  background-color: #fff0e7;
  border-radius: 4px;
}

#moreButton {
  position: absolute;
  top: 34px;
  right: 20px;
}
</style>